package com.rk.user.service.impl;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rk.common.exception.YyghException;
import com.rk.common.result.ResultCodeEnum;
import com.rk.common.util.JwtHelper;
import com.rk.hosp.enums.AuthStatusEnum;
import com.rk.hosp.model.base.BaseEntity;
import com.rk.hosp.model.user.Patient;
import com.rk.hosp.model.user.UserInfo;
import com.rk.hosp.model.user.UserLoginRecord;
import com.rk.hosp.vo.user.LoginVo;
import com.rk.hosp.vo.user.UserAuthVo;
import com.rk.hosp.vo.user.UserInfoQueryVo;
import com.rk.user.mapper.UserInfoMapper;
import com.rk.user.mapper.UserLoginRecordMapper;
import com.rk.user.service.PatientService;
import com.rk.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author :Rk.
 * @date : 2022/11/21
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //校验前端传递过来的参数是否为空
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //校验验证码
        String mobleCode = redisTemplate.opsForValue().get(phone);
        if(!code.equals(mobleCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号码 微信登录
        UserInfo userInfo = null;
        //如果oppenid不为空，去查询user
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.getByOpenid(loginVo.getOpenid());
            //如果查询到了，绑定手机号
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //userInfo=null 说明手机直接登录
        if(null == userInfo) {
            LambdaQueryWrapper<UserInfo> lqm=new LambdaQueryWrapper<>();
            lqm.eq(UserInfo::getPhone,phone);
            userInfo = userInfoMapper.selectOne(lqm);
            //如果没有查到 就添加新用户
            if(userInfo==null){
                userInfo=new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                userInfo.setIsDeleted(0);
                userInfo.setCreateTime(new Date());
                userInfoMapper.insert(userInfo);
            }

        }

        //校验是否被禁用
        if(userInfo.getStatus()==0){
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //记录登录
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(loginVo.getIp());
        userLoginRecordMapper.insert(userLoginRecord);


        //返回首页显示名称
        Map<String,Object> map=new HashMap<>();
        String name=userInfo.getName();

        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }

        //生成token
        String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
        map.put("token", token);
        map.put("name",name);
        return map;

    }

    /**
     * 用户认证
     * @param userId
     * @param userAuthVo
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //设置认证信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        //认证中
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //更新认证
        userInfoMapper.updateById(userInfo);
    }


    /**
     * 分页查询
     * @param pageParam
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {

        //UserInfoQueryVo获取条件值 用户名称/手机号
        String name = userInfoQueryVo.getKeyword();
        //用户状态
        Integer status = userInfoQueryVo.getStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        LambdaQueryWrapper<UserInfo> lqw=new LambdaQueryWrapper<>();

        if(!StringUtils.isEmpty(name)) {
            lqw.like(UserInfo::getName,name);
        }
        if(!StringUtils.isEmpty(status)) {
            lqw.eq(UserInfo::getStatus,status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            lqw.eq(UserInfo::getAuthStatus,authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            lqw.ge(BaseEntity::getCreateTime,createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            lqw.le(BaseEntity::getCreateTime,createTimeEnd);

        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, lqw);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;

    }


    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }


    /**
     * 锁定用户
     *
     * @param userId
     * @param status
     */
    @Override
    public void lockUser(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    /**
     * 查询用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object> showUser(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    /**
     * 认证审批
     *
     * @param userId
     * @param authStatus 2：通过 -1：不通过
     */
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            if(userInfo!=null){
                userInfo.setAuthStatus(authStatus);
                baseMapper.updateById(userInfo);
            }
        }
    }

    /**
     * 根据微信openid获取用户信息
     *
     * @param openid
     * @return
     */
    @Override
    public UserInfo getByOpenid(String openid) {
        return userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));
    }


}
